//
//  CorgiComposeView.swift
//  weibo
//
//  Created by Corgi on 17/3/27.
//  Copyright © 2017年 cocoaHangTou. All rights reserved.
//

import UIKit
import pop

class CorgiComposeView: UIView {
    
    var btnArr: [CorgiComposeButton] = [CorgiComposeButton]()

    var target: UIViewController?
    
    override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    class func show(target: UIViewController) {
        
        let composeView = CorgiComposeView()
        
        composeView.target = target
        
        target.view.addSubview(composeView)
        
        composeView.setupComposeBtnAnimation(isUp: true)
    }

    fileprivate func setupUI() {
        
//        backgroundColor = UIColor.orange
        
        addSubview(BigImageView)
        addSubview(sloganImageView)
        addChildComposeButtons()
        
        BigImageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        sloganImageView.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(50)
        }
    }
    
    
    
    private lazy var BigImageView: UIImageView = {
    
        let img = UIImageView(image: UIImage.getScreenSnap()!.light())
    
        return img
    }()
    
    private lazy var sloganImageView: UIImageView = UIImageView(imageName: "compose_slogan")
}

extension CorgiComposeView {

    fileprivate func setupComposeBtnAnimation(isUp: Bool) {
        
        let flag: CGFloat = isUp == true ? -350 : 350
        
        let tempArr = isUp == true ? btnArr : btnArr.reversed()
        
        for (i, btn) in tempArr.enumerated() {
            
            // 实例化弹簧动画对象
            let anSpring = POPSpringAnimation(propertyNamed: kPOPViewCenter)!
            
            anSpring.toValue = CGPoint(x: btn.center.x, y: btn.center.y + flag)
            // 开始时间 CACurrentMediaTime() 系统绝对时间
            anSpring.beginTime = CACurrentMediaTime() + Double(i)*0.025
            // 振幅
            anSpring.springBounciness = 10.0
            // 设置动画
            btn.pop_add(anSpring, forKey: nil)
            
        /*
             POPSpringAnimation *anSpring = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerPositionX];
             anSpring.toValue = @(self.square.center.y+300);
             anSpring.beginTime = CACurrentMediaTime() + 1.0f;
             anSpring.springBounciness = 10.0f;
             [self.square pop_addAnimation:anSpring forKey:@"position"];
             */
        
            
        }
    }
}

extension CorgiComposeView {

    fileprivate func addChildComposeButtons() {
     
        let composeDataArr = loadComposePlist()
        
        let btnWidth: CGFloat = 80
        let btnHeight: CGFloat = 110
        
        let btnMargin: CGFloat = (screenWidth - 3 * btnWidth) * 0.25
        
        for (i, composeModel) in composeDataArr.enumerated() {
         
            let row = CGFloat(i / 3)
            let colum = CGFloat(i % 3)
            
            let btn = CorgiComposeButton()
            
            btn.composeModel = composeModel
            
            btn.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
            
            btn.setImage(UIImage(named:composeModel.icon ?? ""), for: .normal)
            btn.setTitle(composeModel.title, for: .normal)
            
            btn.frame = CGRect(x: btnMargin + (btnWidth + btnMargin) * colum, y: screenHeight + btnMargin + (btnHeight + btnMargin) * row, width: btnWidth, height: btnHeight)
            
            btnArr.append(btn)
            
            addSubview(btn)
        }
    }
    
    @objc fileprivate func buttonClick(button: CorgiComposeButton) {
        
        UIView.animate(withDuration: 0.25, animations: {
            
            for composeBtn in self.btnArr {
            
                composeBtn.alpha = 0.2
            
                if composeBtn == button {
                
                    composeBtn.transform = CGAffineTransform(scaleX: 2, y: 2)
                
                } else {
                
                    composeBtn.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
                }
            }
            
        }) { (_) in
            UIView.animate(withDuration: 0.25, animations: {
                
                for composeBtn in self.btnArr {
                
                    composeBtn.alpha = 1
                    
                    composeBtn.transform = CGAffineTransform.identity
                }
            }, completion: { (_) in
                
                guard let className = button.composeModel?.classname else {
                
                    return
                }
                
                guard let classType = NSClassFromString(className) as? UIViewController.Type else {
                
                    return
                }
                
                let vc = classType.init()
                
                self.target?.present(CorgiNavigationController(rootViewController: vc), animated: true, completion: {
                    
                    self.removeFromSuperview()
                })
            })
        }
    }
    
    fileprivate func loadComposePlist() -> [CorgiComposeModel]{
        
        let filePath = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        
        let plistArr = NSArray(contentsOfFile: filePath)!
        
        let tempArr = NSArray.yy_modelArray(with: CorgiComposeModel.self, json: plistArr) as! [CorgiComposeModel]
        
        return tempArr
    }
}


extension CorgiComposeView {

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        setupComposeBtnAnimation(isUp: false)
        
        //延迟
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.4) {
            
            self.removeFromSuperview()
        }
    }

}
